<template>
  <div>
    <h2>会员卡查询</h2>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/AdminMain/AdminHome">主页</el-breadcrumb-item>
      <el-breadcrumb-item>会员卡查询</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <i class="el-icon-s-order" style="margin-right: 5px;"></i>会员卡查询
        </div>
      </template>

      <el-form :inline="true" @submit.prevent="onSearch">
        <el-form-item>
          <el-input v-model="searchAccount" placeholder="请输入会员账号/卡号"
                    onkeypress="return event.keyCode>=48&&event.keyCode<=57" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="memberAccount" label="会员账号/卡号" />
        <el-table-column prop="memberName" label="姓名" />
        <el-table-column prop="cardTime" label="办卡时间" :formatter="formatDate"/>
        <el-table-column prop="memberGender" label="性别" />
        <el-table-column prop="memberAge" label="年龄" />
        <el-table-column prop="memberPhone" label="联系方式" />
        <el-table-column prop="memberHeight" label="身高" />
        <el-table-column prop="memberWeight" label="体重" />
        <el-table-column prop="cardClass" label="购买课时" />
        <el-table-column prop="cardNextClass" label="剩余课时" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" @click="onEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref} from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'
import dayjs from 'dayjs'

const searchAccount = ref('')
const tableData = ref([])

const router = useRouter()

const onSearch = () => {
  if (!searchAccount.value) {
    ElMessage.warning('请输入会员账号/卡号')
    return
  }
  axios.get('/server/member/selMemberByMemberAccount', {
    params: { memberAccount: searchAccount.value },
    headers: {
      'Authorization': localStorage.getItem('token')
    },
    withCredentials: true
  })
      .then(response => {
        const res = response.data
        if (res.code === 200) {
          // ⚠ 包装成数组
          tableData.value = res.data ? [res.data] : []
          if (!res.data) {
            ElMessage.info('未找到符合条件的数据')
          }
        } else {
          ElMessage.error(res.message || '查询失败')
        }
      })
    .catch(() => {
      ElMessage.error('请求失败')
    })
}

const onEdit = (row) => {
  router.push({ path: '/AdminMain/EditMember', query: { memberAccount: row.memberAccount } })
}

const formatDate = (row, column, cellValue) => {
  return cellValue ? dayjs(cellValue).format('YYYY-MM-DD') : ''
}

</script>
